<?php
class Core_Frontend_Plugin_Output_Rewrite extends Dcmp_Plugin_Base{
	
	public function execute(){
        $content = $this->getResponse()->getContent();
        $content = $this->rewriteCustomerCard($content);
        $this->getResponse()->setContent($content);	
	}
	
	private function rewriteCustomerCard($content){
		if (preg_match_all('/\{\{rewrite\s"(\/customer\/shop\/card\/id\/(\d+))"\}\}/iU', $content, $matches)) {
			$atts = $matches[0];
			$sourceUrls = $matches[1];
			$ids = $matches[2];
						
			$sefUrls = App::getModel('website/collection_sef')
						->filterBySourceIds($ids)
						->filterBySourceType('card')
						->load();
						
			$attCount = count($atts);
			for($i = 0; $i < $attCount; $i++){
				$id = $ids[$i];
				$att = $atts[$i];
				$sourceUrl = $sourceUrls[$i];
				$found = FALSE;
				foreach($sefUrls as $sefUrl){
					if(strcmp($sefUrl->getSourceId(), $id) == 0){
						$content = str_replace($att, $sefUrl->getRewriteUrl().'.html', $content);
						$found = TRUE;
						break;
					}
				}
				if(!$found){
					$content = str_replace($att, $sourceUrl, $content);
				}
			}
		}
        return $content;
	}
}